Imports Microsoft.VisualBasic
Imports System.Collections.Generic
Imports System.Data.SqlClient

Namespace MyDAO
    Public Class UpdateStringBuilder
        Inherits AssignmentStringBuilder

        Public Sub New(ByVal tableName As String)
            MyBase.New(tableName)
        End Sub

        Public Sub New(ByVal tableName As String, ByVal aliasName As String)
            MyBase.New(tableName, aliasName)
        End Sub

        Public Assignments As New List(Of MyDataAssignStatement)

        Public Sub AddColumnAssignment(ByVal columnName As String, ByVal selectColumnName As String)
            Me.Assignments.Add(New MyDataAssignStatement(columnName, New MyColumnExpression(selectColumnName)))
        End Sub

        Public Overrides Sub AddAssignment(ByVal columnName As String, ByVal value As Object)
            Me.AddVarAssignment(columnName)
            Me.AddWithValue(columnName, value)
        End Sub

        Public Sub AddVarAssignment(ByVal columnName As String)
            Me.AddVarAssignment(columnName, columnName)
        End Sub

        Public Sub AddVarAssignment(ByVal columnName As String, ByVal variable As String)
            Me.Assignments.Add(New MyDataAssignStatement(columnName, New MyVariableExpression(variable)))
        End Sub

        Public Overrides Function Build() As MyStringBuilder
            Dim sql As New MyStringBuilder

            If Me.Table.AliasName = "" Then
                sql.AppendFormat("update {0} set ", Me.Table)
            Else
                sql.AppendFormat("update {0} set ", Me.Table.AliasName)
            End If

            Dim expressions As New List(Of String)

            'assignment
            expressions.Clear()

            For Each assignment As MyDataAssignStatement In Me.Assignments
                expressions.Add(assignment.ToString())
            Next

            sql.AppendFormat(String.Join(",", expressions.ToArray()))
            sql.AppendFormat(" ")

            'table
            sql.AppendFormat("from {0} ", Me.Table)

            'join
            expressions.Clear()

            For Each relation As MyDataRelationBase In Me.Relations
                'sql.AppendFormat("
                expressions.Add(relation.ToString())
            Next

            sql.AppendFormat(String.Join(" ", expressions.ToArray()))
            sql.AppendFormat(" ")

            'condition
            If Me.Condition IsNot Nothing Then
                sql.AppendFormat("where ")
                sql.AppendFormat(Me.Condition.ToString())
            End If

            Return sql
        End Function

    End Class
End Namespace
